
const { ListNode, LinkedList } = require('../2. 链表/1. 链表基础/1. 建立线性链表.js')
// 给你单链表的头指针head和两个整数left和right，其中left <= right，请你反转从位置left到right的链表节点，返回反转后的链表

function reverseBetween(head, left, right) {
    let dummyHead = new ListNode(0, head)
    let leftNode = dummyHead
    for (let i = 0; i < left - 1; i++) {
        leftNode = leftNode.next        
    }
    let rightNode = leftNode
    // 这里的遍历范围计算要注意，因为此时leftNode为left位置的前一位，
    // 而我们找到right的后一位，所以要多走两步
    for (let i = 0; i <= right - left + 1; i++) {
        rightNode = rightNode.next
    }
    reverse(leftNode, rightNode)
    return dummyHead.next

}

function reverse(head, tail) {
    let pre = head
    let cur = pre.next
    let first =cur
    while (cur !== tail) {
        let temp = cur.next
        cur.next = pre
        pre = cur
        cur = temp
    }
    head.next = pre
    first.next = tail
}

let head = [1, 2, 3, 4, 5], left = 1, right = 2
let node = new LinkedList(head)

console.log(reverseBetween(node.head, left, right));